import React, { Component } from 'react';
import moment from 'moment'; //time格式工厂
import style from './RoleManage.less';
import { connect } from 'dva';
import { FormattedMessage, formatMessage } from 'umi/locale'; //此方法引入的数据可以在src/locales中配置
import {
  Button,
  Input,
  DatePicker,
  Form,
  Row,
  Col,
  Table,
  Modal,
  Select,
  Card,
  PageHeader,
  Alert,
  Pagination,
  Upload,
  message,
  Icon,
} from 'antd';

//日期插件
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

//表单
const FormItem = Form.Item;
const { TextArea } = Input;

//所属租户选择框
const Option = Select.Option;

//命名空间
const namespace = 'RoleManage';

const mapDispatchToProps = function(dispatch) {
  return {
    dispatch: dispatch,
  };
};

@connect(mapDispatchToProps)
@Form.create()
class ModalBox extends Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.props.dispatch({
      type: `${namespace}/findAll`,
      payload: {
      },
      callback: (res) => {
        this.setState({
          tenantList: res.data,
        })
        if (res && res.data && res.data.length === 1){
          this.setState({
            tenantId: res.data[0].tenant_id,
          })
        } else {
          console.log("123")
        }
      }
    })
  }
  state ={
    //确定按钮状态
    loading: false,
    tenantList:[],
    tenantId:""
  }

  //点击确定
  onOk = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        //避免重复点击确定按钮
        this.setState({
          loading: true,
        });
        this.loadingTimer = setTimeout(() => {
          this.setState({
            loading: false,
          });
        }, 1000);
        //关闭模态框
        this.props.childModalChangeModalState({
          visible: true,
        });
        //重置表单
        this.props.form.resetFields();
        if (this.state.tenantList.length === 1) {
          values.tenant_id = this.state.tenantId;
        }
        this.props.dispatch({
          type: `${namespace}/addBegin`,
          payload: {
            values: values,
          },
          callback: res => {
            if (res.return_code === 'SUCCESS') {
              message.success('新增成功');
              //代入当前分页状态重新查询一次
              this.props.dispatch({
                type: `${namespace}/selectBegin`,
                payload: {
                  page_size: this.props.page_size,
                  page_num: 1,
                },
              });
              //页码状态同步复位 清空搜索表单状态
              this.props.clearSearchForm();
            } else {
              //只有角色创建失败时需要重新查询一次
              this.props.dispatch({
                type: `${namespace}/selectBegin`,
                payload: {
                  page_size: this.props.page_size,
                  page_num: this.props.page_num,
                  ...this.props.searchFormNow,
                },
              });
            }
          },
        });
      } else {
        return false;
      }
    });
  };

  componentWillUnmount(){
    //清除定时器，防止内存泄露
    clearTimeout(this.loadingTimer);
  }

  render() {
    const { dispatch, form } = this.props;
    const {
      form: { getFieldDecorator, getFieldValue, getFieldsValue, setFieldsValue, resetFields },
      nowRow,
    } = this.props;

    //规则就是用来打破的
    const role_name_rules = {
      rules: [
        {
          required: true,
          message: '必须填写一个角色名称',
        },
        {
          min: 1,
          max: 15,
          message: '角色名称应在15个字符内',
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能使用空格',
        },
      ],
    };
    const role_tenant_rules = {
      rules: [
        {
          required: true,
          message: '请选择',
        },
      ],
    }
    const description_rules = {
      rules: [
        {
          min: 0,
          max: 255,
          message: '详情不应该超过255个字符',
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '(不能包含空格)',
        }
      ],
    };
    return (
      <div>
        <Modal
          visible={this.props.visible}
          title={`创建角色`}
          onCancel={this.props.hideCancel}
          childModalChangeModalState={this.props.childModalChangeModalState}
          destroyOnClose={true}
          maskClosable={false}
          bodyStyle={{
            width: 800,
          }}
          width="800px"
          page_size={this.props.page_size}
          footer={[
            <Button key="back" onClick={this.props.hideCancel}>
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={this.onOk}
              loading={this.state.loading}
            >
              提交
            </Button>,
          ]}
        >
          <Form layout="inline">
            {/* 行1 */}
            <div className={style['motal-line']}>
              <div className={style['every-block']}>
                <p className={style.p1}>
                  <span className={style.star}>*</span>
                  {formatMessage({ id: 'iot.roleManage.roleManage_list.role_name' })}：
                </p>
                <Form.Item style={{ marginBottom: 0 }}>
                  {getFieldDecorator('role_name', role_name_rules)(
                    <Input className={style['input-box']} />
                  )}
                </Form.Item>
              </div>
            </div>
            {
              this.state.tenantList.length > 1 ?
                <div className={style['motal-line']}>
                  <div className={style['every-block']}>
                    <p className={style.p1}>
                      <span className={style.star}>*</span>
                      {formatMessage({ id: 'iot.organization.organization_search.tenant_name' })}：
                    </p>
                    <Form.Item style={{ marginBottom: 0 }}>
                      {getFieldDecorator('tenant_id', role_tenant_rules)(
                        <Select className={style['input-box']}>
                          {this.state.tenantList && this.state.tenantList.length>0 ?
                            this.state.tenantList.map(function (item) {
                              return <Option key= {item.tenant_id} id={item.tenant_id}
                                             value={item.tenant_id}>{item.tenant_name}
                              </Option>;
                            }) : []
                          }
                        </Select>
                      )}
                    </Form.Item>
                  </div>
                </div>
                :
                null
            }

            {/* 文本 */}
            <div className={style['motal-line']} style={{ height: 100 }}>
              <p className={style.p2}>
                {formatMessage({ id: 'iot.roleManage.roleManage_list.description' })}：
              </p>
              <Form.Item style={{ marginBottom: 0 }}>
                {getFieldDecorator('description', description_rules)(
                  <TextArea rows={4} style={{ float: 'left', width: 620 }} />
                )}
              </Form.Item>
            </div>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default ModalBox;
